﻿using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Internal.Mapping.Voxel.Controls.DataFilter;
using Aspose.Cells;
using CCTool.Scripts.Manager;
using CCTool.Scripts.ToolManagers.Extensions;
using CCTool.Scripts.ToolManagers.Library;
using CCTool.Scripts.ToolManagers.Managers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Polygon = ArcGIS.Core.Geometry.Polygon;
using Polyline = ArcGIS.Core.Geometry.Polyline;

namespace CCTool.Scripts.ZT.QJ
{
    /// <summary>
    /// Interaction logic for CreateJZBSB.xaml
    /// </summary>
    public partial class CreateJZBSB : ArcGIS.Desktop.Framework.Controls.ProWindow
    {
        // 定义一个进度框
        private ProcessWindow processwindow = null;
        string tool_name = "生成界址标示表";

        public CreateJZBSB()
        {
            InitializeComponent();

            // 初始化参数选项
            textFolderPath.Text = BaseTool.ReadValueFromReg(tool_name, "textFolder");
        }

        private void combox_zd_DropDown(object sender, EventArgs e)
        {
            UITool.AddFeatureLayerAndTableToComboxPlus(combox_zd);
        }

        private void openFolderButton_Click(object sender, RoutedEventArgs e)
        {
            textFolderPath.Text = UITool.OpenDialogFolder();
        }

        private void btn_help_Click(object sender, RoutedEventArgs e)
        {
            string url = "";
            UITool.Link2Web(url);
        }

        private async void btn_go_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 获取数据
                string zd = combox_zd.ComboxText();

                string startPoint = combox_startPoint.ComboxText();
                string endPoint = combox_endPoint.ComboxText();
                string jzxlb = combox_jzxlb.ComboxText();
                string jzxwz = combox_jzxwz.ComboxText();
                string jbzl = combox_jbzl.ComboxText();

                string textFolder = textFolderPath.Text;

                // 写入本地
                BaseTool.WriteValueToReg(tool_name, "textFolder", textFolder);

                // 判断参数是否选择完全
                if (zd == "" || textFolder == "" || startPoint == "" || endPoint == "" || jzxlb == "" || jzxwz == "" || jbzl == "")
                {
                    MessageBox.Show("有必选参数为空！！！");
                    return;
                }

                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);

                Close();

                await QueuedTask.Run(() =>
                {
                    // 检查数据
                    List<string> fields = new List<string>()
                    {
                        startPoint, endPoint, jzxlb, jzxwz, jbzl
                    };
                    List<string> errs = CheckData(zd, fields);
                    // 打印错误
                    if (errs.Count > 0)
                    {
                        foreach (var err in errs)
                        {
                            pw.AddMessageMiddle(10, err, Brushes.Red);
                        }
                        return;
                    }

                    // 复制地籍调查表Excel
                    string excelPath = @$"{textFolder}\界址标示表_{zd}.xls";
                    DirTool.CopyResourceFile(@"CCTool.Data.Excel.杂七杂八.权籍调查_界址标示表.xls", excelPath);
                    // 获取工作薄、工作表
                    string excelFile = ExcelTool.GetPath(excelPath);
                    int sheetIndex = ExcelTool.GetSheetIndex(excelPath);
                    // 打开工作薄
                    Workbook wb = ExcelTool.OpenWorkbook(excelFile);

                    // 处理sheet
                    Worksheet ws = wb.Worksheets["界址标示表"];
                    Cells cells = ws.Cells;

                    int index = 5;   // 起始行
                    int ptDigit = 2;

                    // 页数
                    long pageCount = (long)Math.Ceiling((double)zd.GetFeatureCount() / 21);

                    // 每页行数
                    int rowCount = 47;
                    // 如果多于1页，就复制
                    if (pageCount > 1)
                    {
                        // 复制分页，前两页已有不用复制
                        for (int k = 0; k < pageCount - 1; k++)
                        {
                            cells.CopyRows(cells, 0, (k + 1) * rowCount, rowCount);
                        }
                    }

                    FeatureClass featureClass = zd.TargetFeatureClass();
                    RowCursor cursor = featureClass.Search();
                    while (cursor.MoveNext())
                    {
                        Feature feature = cursor.Current as Feature;
                        Polyline polyline = feature.GetShape() as Polyline;
                        // 获取指标
                        string sp = feature[startPoint]?.ToString() ?? "";
                        string ep = feature[endPoint]?.ToString() ?? "";
                        string xlb = feature[jzxlb]?.ToString() ?? "";
                        string xwz = feature[jzxwz]?.ToString() ?? "";
                        string jb = feature[jbzl]?.ToString() ?? "";

                        // 属性转换
                        int jb_int = jb switch
                        {
                            "钢钉" => 1,
                            "混凝土桩" => 2,
                            "喷涂" => 3,
                            _ => 0,
                        };
                        int xlb_int = xlb switch
                        {
                            "道路" => 9,
                            "沟渠" => 10,
                            "围墙" => 11,
                            "墙壁" => 12,
                            "空地" => 13,
                            "田埂" => 14,
                            "滴水线" => 15,
                            "其他" => 16,
                            _ => 0,
                        };
                        int xwz_int = xwz switch
                        {
                            "内" => 17,
                            "中" => 18,
                            "外" => 19,
                            _ => 0,
                        };

                        // 写入属性
                        if (jb_int > 0) { cells[index, jb_int].Value = $"√"; }

                        // 写入点号
                        cells[index, 0].Value = sp;
                        // 写入距离
                        if (index % rowCount == 5)
                        {
                            cells[index, 8].Value = polyline.Length;
                            if (xlb_int > 0) { cells[index, xlb_int].Value = $"√"; }
                            if (xwz_int > 0) { cells[index, xwz_int].Value = $"√"; }
                        }
                        else
                        {
                            cells[index + 1, 8].Value = polyline.Length;
                            if (xlb_int > 0) { cells[index + 1, xlb_int].Value = $"√"; }
                            if (xwz_int > 0) { cells[index + 1, xwz_int].Value = $"√"; }
                        }

                        // 设置单元格为数字型，小数位数
                        Aspose.Cells.Style style = cells[index - 1, 8].GetStyle();
                        style.Number = 4;   // 数字型
                        style.Custom = ptDigit switch
                        {
                            1 => "0.0",
                            2 => "0.00",
                            3 => "0.000",
                            4 => "0.0000",
                            _ => null,
                        };
                        // 设置
                        cells[index - 1, 8].SetStyle(style);
                        cells[index, 8].SetStyle(style);

                        // 行变化
                        if (index % rowCount == 5)
                        {
                            index += 1;
                        }
                        else if (index % rowCount == 44)
                        {
                            index += 8;
                        }
                        else
                        {
                            index += 2;
                        }
                    }

                    // 保存
                    wb.Save(excelFile);
                    wb.Dispose();

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private List<string> CheckData(string zd, List<string> fields)
        {
            List<string> result = new List<string>();

            // 检查字段值是否符合要求
            string result_value = CheckTool.CheckFieldValueSpace(zd, fields);
            if (result_value != "")
            {
                result.Add(result_value);
            }

            return result;
        }

        private void combox_startPoint_DropDown(object sender, EventArgs e)
        {
            UITool.AddTextFieldsToComboxPlus(combox_zd.ComboxText(), combox_startPoint);
        }

        private void combox_endPoint_DropDown(object sender, EventArgs e)
        {

            UITool.AddTextFieldsToComboxPlus(combox_zd.ComboxText(), combox_endPoint);
        }

        private void combox_jzxlb_DropDown(object sender, EventArgs e)
        {

            UITool.AddTextFieldsToComboxPlus(combox_zd.ComboxText(), combox_jzxlb);
        }

        private void combox_jbzl_DropDown(object sender, EventArgs e)
        {

            UITool.AddTextFieldsToComboxPlus(combox_zd.ComboxText(), combox_jbzl);
        }

        private void combox_jzxwz_DropDown(object sender, EventArgs e)
        {

            UITool.AddTextFieldsToComboxPlus(combox_zd.ComboxText(), combox_jzxwz);
        }

        private async void combox_zd_Closed(object sender, EventArgs e)
        {
            // 如果图层有指定的字段，则添加到combox中
            try
            {
                string zd = combox_zd.ComboxText();
                await UITool.InitLayerFieldToComboxPlus(combox_startPoint, zd, "SJZDH", "string");
                await UITool.InitLayerFieldToComboxPlus(combox_endPoint, zd, "EJZDH", "string");
                await UITool.InitLayerFieldToComboxPlus(combox_jzxlb, zd, "界址线", "string");
                await UITool.InitLayerFieldToComboxPlus(combox_jbzl, zd, "界标类", "string");
                await UITool.InitLayerFieldToComboxPlus(combox_jzxwz, zd, "界址_1", "string");
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }

        }
    }
}
